// TODO: CODE REVIEW & CLEANUP!
//
// MusicFoundArtistsScreen.xaml.cs
//

using System;
using System.Windows;
using System.Windows.Controls;
using System.Xml;
using HomeUX.ClientAppSupport;
using HomeUX.ClientControlSupport;
using HomeUX.Controls;
using HomeUX.Synchronization;
using HomeUX.Utilities;

namespace HomeUX.MusicClientLibrary
{

public partial class MusicFoundArtistsScreen : UserControl
{
    MusicClientHelper _musicClientHelper;
    Style _musicTextStyle;

    bool _isDirty = true;
    string _find;

    /// <summary>
    /// A <n>String.Format</n>-style format string to use for <n>HeaderTextBlock</n>.  Initialized
    /// from the design-time text value of  <n>HeaderTextBlock</n>.
    /// </summary>
    string _headerFormatString;

    // query string -- set by a "caller" before navigating here
    public string Find
    {
        get
        {
            return _find;
        }
        set
        {
            _find = value;
            _isDirty = true;
        }
    }

    public MusicFoundArtistsScreen()
    {
        InitializeComponent();

        // initialize <_headerFormatString>
        _headerFormatString = HeaderTextBlock.Text;

        Loaded += MusicFoundArtistsScreen_Loaded;
        GotFocus += MusicFoundArtistsScreen_GotFocus;
    }

    void MusicFoundArtistsScreen_Loaded(object sender, RoutedEventArgs e)
    {
        _musicTextStyle = (Style)LayoutRoot.Resources["MusicTextStyle"];

        _musicClientHelper = new MusicClientHelper(this, BeginLoadingDataFromMusicServer,
            OnParcelReceived);

        _musicClientHelper.Screen.Opened += OnScreenOpened;
    }

    void OnScreenOpened(object sender, EventArgs e)
    {
        // if the required properties were not set correctly before navigating to this screen,
        // this screen is in an error state
        if (Find == null)
        {
            _musicClientHelper.SetErrorState();
            return;
        }

        if (_isDirty)
        {
            HeaderTextBlock.Text = String.Format(_headerFormatString, Find,
                _musicClientHelper.MusicDeviceName);

            // do the same thing we'd do if we were waiting for the music server to become available
            _musicClientHelper.TryToLoadData();
        }
    }

    void BeginLoadingDataFromMusicServer()
    {
        ArtistsListBox.Items.Clear();

        string command = ParsedSyncNodeCommand.Format("Search",
             "RecipientId", XmlConvert.ToString(_musicClientHelper.RecipientId),
             "Find", Find,
             "MaxArtists", "9999",
             "MaxAlbums", "-1",
             "MaxTracks", "-1");

        _musicClientHelper.MusicDeviceNode.ExecuteCommand(command);
    }

    void OnParcelReceived(Guid recipientId, XmlReader reader)
    {
        try
        {
            foreach (XmlElementInfo element in XmlElementInfo.EnumerateElements(reader))
            {
                switch (element.Name)
                {

                case "FoundArtist":

					AddArtistToList(element.GetRequiredAttribute("ArtistName"));
					break;

                case "/DoneSearch":

                    _musicClientHelper.OnDataLoaded();
                    _isDirty = false;
                    break;

                }
            }
        }
        catch (InvalidOperationException ex)
        {
            ClientGlobals.Alert(AlertType.Warning,
                "Invalid reply from server: {0}", ex.Message);
        }
    }

    /// <summary>
    /// Called when the request begun by <r>RequestArtists</r> has completed.  This method is
    /// called once for each artist.
    /// </summary>
    void AddArtistToList(string name)
    {
        var textBlock = new TextBlock()
        {
            Text = name,
            Tag = name,
            Style = _musicTextStyle
        };
        ArtistsListBox.Items.Add(textBlock);
    }

    void MusicFoundArtistsScreen_GotFocus(object sender, RoutedEventArgs e)
    {
        ArtistsListBox.Focus();
    }

    private void ArtistsListBox_ItemClick(object sender, ItemClickEventArgs e)
    {
        string artistName = (string) e.ItemValue;

        Screen screen;
        MusicArtistScreen screenControl;
        _musicClientHelper.FindMusicScreen("Artist", out screen, out screenControl);
        screenControl.ArtistName = artistName;
        screen.GoTo();
    }
}

}

